<?php

namespace app\util\rke;

use think\Facade\Env;
use app\util\rke\AioServe;

class AioBase
{
    /**
     * 获取消息ID
     * @return string
     */
    protected static function getMessageId()
    {
        return rand(100000000, 999999999) . uniqid() . time();
    }

    /**
     * 发送消息
     * @param $facesluiceId
     * @param $data
     * @param int $qos
     * @return bool
     */
    protected static function createPublish($facesluiceId, $data, $qos = 0)
    {
        $config = [
            'host' => Env::get('FACE_DEVICE.FD_HOST', '127.0.0.1'),
            'port' => Env::get('FACE_DEVICE.FD_PORT', 61613),
            'username' => Env::get('FACE_DEVICE.FD_USERNAME', ''),
            'passwd' => Env::get('FACE_DEVICE.FD_PASSWORD', ''),
            'client_id' => self::getMessageId()
        ];
        $mqtt = new AioServe($config['host'], $config['port'], $config['client_id']);
//        $mqtt->debug = true;
        if ($mqtt->connect(true, NULL, $config['username'], $config['passwd'])) {
            $data = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            $mqtt->publish('mqtt/face/' . $facesluiceId, $data, ['qos' => $qos]);
            $mqtt->close();
            return true;
        } else {
            return false;
        }
    }
}